package org.extframework.ld.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : Dong.Li
 * @created : 2013-1-17
 * @version : 1.0
 * @description :
 */
public class UtilJSON {

	private final Pattern textPattern = Pattern.compile("text:'(.*)',");
	private final Pattern idPattern = Pattern.compile("id:'(.*)'");

	private static final Pattern patternStore = Pattern
			.compile(":.*\"(.*)\".*}");
	private static final Pattern urlPattern = Pattern
			.compile("(?i)^http://.*$|.html$|.*.com$|.*.cn$|.*.org$|.*.net$");

	public static synchronized String[] changeStore(String store) {
		List strList = new ArrayList();
		String[] strs = store.split(",");
		for (String str : strs) {
			Matcher matcher = patternStore.matcher(str.trim());
			if (matcher.find()) {
				strList.add(matcher.group(1).replaceAll("\\.", "_"));
			}
		}
		return ((String[]) strList.toArray(new String[0]));
	}

	public static synchronized String toJSON(List<Object[]> los, String store) {
		String[] strs = changeStore(store);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < los.size(); ++i) {
			sb.append("{");
			for (int j = 0; j < ((Object[]) los.get(i)).length; ++j) {
				sb.append(strs[j]);
				sb.append(":\"");
				if ((((Object[]) los.get(i))[j] == null)
						|| (((Object[]) los.get(i))[j].toString().length() == 0)) {
					sb.append("-");
				} else if (((Object[]) los.get(i))[j] instanceof Date) {
					Date date = (Date) ((Object[]) los.get(i))[j];
					sb.append(DateUtil.formatDateDayHs(date));
				} else if (((Object[]) los.get(i))[j] instanceof Boolean) {
					sb.append((((Boolean) ((Object[]) los.get(i))[j])
							.booleanValue()) ? "是" : "否");
				} else {
					sb.append(((Object[]) los.get(i))[j]);
				}

				sb.append("\"");
				if (j != ((Object[]) los.get(i)).length - 1) {
					sb.append(",");
				}
			}
			sb.append("}");
			if (i != los.size() - 1) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

}
